import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'models/user_model.dart';
import 'screens/home_screen.dart';
import 'screens/exam_list_screen.dart';
import 'screens/login_screen.dart';
import 'screens/log_view_screen.dart';
import 'services/exam_service.dart';
import 'services/auth_service.dart';
import 'utils/responsive_util.dart';
import 'services/user_log_service.dart';
import 'data/user_data.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';
import 'package:flutter/services.dart';
import 'services/student_service.dart';
import 'services/device_config_service.dart';
import 'services/dedicated_device_monitor_service.dart';
import 'services/device_info_service.dart';
import 'package:package_info_plus/package_info_plus.dart';

class AppLifecycleLogger extends StatefulWidget {
  final Widget child;
  const AppLifecycleLogger({required this.child, super.key});

  @override
  State<AppLifecycleLogger> createState() => _AppLifecycleLoggerState();
}

class _AppLifecycleLoggerState extends State<AppLifecycleLogger> with WidgetsBindingObserver {
  AppLifecycleState? _lastState;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) async {
    if (_lastState == state) return;
    _lastState = state;
    final user = UserData.currentUser;
    if (user == null) return;
    // 获取当前页面路由名
    String page = ModalRoute.of(context)?.settings.name ?? 'unknown';
    String action = (state == AppLifecycleState.paused || state == AppLifecycleState.inactive)
      ? 'background' : (state == AppLifecycleState.resumed ? 'foreground' : 'other');
    if (action == 'other') return;
    await UserLogService.addLog(UserLog(
      timestamp: DateTime.now(),
      userName: user.name,
      page: page,
      action: action,
    ));
  }

  @override
  Widget build(BuildContext context) {
    return widget.child;
  }
}

void main() async {
  // 确保Flutter初始化完成
  WidgetsFlutterBinding.ensureInitialized();
  
  // 设置全屏和隐藏系统按键
  SystemChrome.setEnabledSystemUIMode(
    SystemUiMode.immersiveSticky,
    overlays: [], // 清空overlays使其完全隐藏状态栏和导航栏
  );
  
  // 强制竖屏
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);
  
  // 异步初始化服务
  await UserData.init(); // 初始化用户数据（加载保存的密码）
  await ExamService.init();
  await AuthService.init(); // 这会初始化StudentService
  await DeviceInfoService.init(); // 初始化设备信息服务
  
  // 确保专用设备目录存在
  await DeviceConfigService.ensureDedicatedDeviceDirectories();
  
  // 自动加载外部目录下的试题、学生、须知文件
  await _autoLoadExternalFiles();
  debugPrint('自动加载外部目录下的试题、学生、须知文件完成');
  
  // 启动专用设备监控服务
  await DedicatedDeviceMonitorService.startMonitoring();
  
  // 运行应用
  runApp(const AppLifecycleLogger(child: MyApp()));
}

Future<void> _autoLoadExternalFiles() async {
  try {
    String? dirPath;
    debugPrint('======Platform.isAndroid: ${Platform.isAndroid}');
    if (Platform.isAndroid) {
      debugPrint('======Platform.isAndroid: ${Platform.isAndroid}');
      // 使用package_info_plus获取包名
      final info = await PackageInfo.fromPlatform();
      final packageName = info.packageName;
      debugPrint('======packageName: $packageName');
      dirPath = '/storage/emulated/0/Android/data/$packageName/files';
      debugPrint('======dirPath: $dirPath');
    } else {
      final directory = await getApplicationDocumentsDirectory();
      dirPath = '${directory.path}/ExamApp';
    }
    final dir = Directory(dirPath);
    debugPrint('======dir: $dir');

    if (!await dir.exists()) return;
    final files = dir
        .listSync()
        .whereType<File>()
        .where((f) {
          final name = f.path.split('/').last;
          return name == '学生信息.xlsx' || name == '学生信息.xls' ||
                 name == '考试须知.xlsx' || name == '考试须知.xls' ||
                 RegExp(r'^(.+)_(.+)_(\d+)_(\d+)\.xlsx$').hasMatch(name) ||
                 RegExp(r'^(.+)_(.+)_(\d+)_(\d+)\.xls$').hasMatch(name);
        })
        .toList();
    print('======files: $files');
    for (final file in files) {
      final filename = file.path.split('/').last;
      debugPrint('filename: $filename');
      if (filename == '学生信息.xlsx' || filename == '学生信息.xls') {
        await StudentService.importFromExcel(file);
      } else if (filename == '考试须知.xlsx' || filename == '考试须知.xls') {
        // TODO: 如有须知导入逻辑可在此补充
      } else {
        // 匹配"试卷ID_试卷名称_试卷序号_考试时间.xlsx"或"试卷ID_试卷名称_试卷序号_考试时间.xls"格式
        final matchXlsx = RegExp(r'^(.+)_(.+)_(\d+)_(\d+)\.xlsx$').firstMatch(filename);
        final matchXls = RegExp(r'^(.+)_(.+)_(\d+)_(\d+)\.xls$').firstMatch(filename);
        final match = matchXlsx ?? matchXls;
        if (match != null) {
          final examId = match.group(1)!;  // 试卷ID
          final examTitle = match.group(2)!;  // 试卷名称
          final examSequence = match.group(3)!;  // 试卷序号
          final durationStr = match.group(4)!;  // 考试时间
          final sequence = int.tryParse(examSequence) ?? 1;  // 默认序号1
          final duration = int.tryParse(durationStr) ?? 60;  // 默认60分钟

          debugPrint('检测到试卷文件，试卷id: $examId, 标题: $examTitle, 序号: $sequence, 时长: $duration分钟');

          final exam = await ExamService.createExamFromExcelFile(
            file,
            title: examTitle,
            description: examTitle,
            duration: duration,
            originalId: examId,
            sequence: sequence,
          );
          
          if (exam == null) {
            debugPrint('试题导入失败');
          } else {
            debugPrint('试题导入成功，题目数：${exam.questions.length}，时长：$duration分钟');
          }
        }
      }
    }
  } catch (e) {
    // 静默失败
    debugPrint('自动加载外部目录下的试题、学生、须知文件失败: $e');
  }
}



class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '考培系统',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
        useMaterial3: true,
        // 使用更简单的方式设置文本样式
        textTheme: const TextTheme(
          bodyLarge: TextStyle(fontSize: 16.0),
          bodyMedium: TextStyle(fontSize: 14.0),
          titleLarge: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
          titleMedium: TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold),
        ),
      ),
      builder: (context, child) {
        // 使用固定文本缩放因子 1.0 代替动态计算
        final mediaQueryData = MediaQuery.of(context);
        
        return MediaQuery(
          data: mediaQueryData.copyWith(
            textScaler: TextScaler.linear(1.0), // 使用固定值 1.0
          ),
          child: child!,
        );
      },
      home: const WelcomeScreen(),
      routes: {
        '/login': (context) => const LoginScreen(),
        '/exam_list': (context) => const ExamListScreen(),
        '/log_view': (context) => const LogViewScreen(),
      },
      onGenerateRoute: (settings) {
        if (settings.name == '/home') {
          // 从路由参数中获取初始标签页索引
          final Map<String, dynamic>? args = settings.arguments as Map<String, dynamic>?;
          final int initialTab = args != null && args.containsKey('initialTab') ? args['initialTab'] : 0;
          return MaterialPageRoute(
            builder: (context) => HomeScreen(initialTab: initialTab),
          );
        }
        return null;
      },
    );
  }
}

class WelcomeScreen extends StatelessWidget {
  const WelcomeScreen({super.key});

  @override
  Widget build(BuildContext context) {
    // 优化布局使内容在一屏内显示完整
    const double borderRadius = 25.0;
    const double standardSpacing = 12.0;
    
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Colors.blue.shade900,
              Colors.blue.shade800,
              Colors.blue.shade400,
            ],
          ),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 40.0), // 减小顶部空间
            // Header - 减小高度
            Padding(
              padding: EdgeInsets.all(standardSpacing),
              child: Row(
                children: [
                  // 应用图标
                  Container(
                    padding: const EdgeInsets.all(8.0),
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.2),
                      borderRadius: BorderRadius.circular(25.0),
                    ),
                    child: const Icon(
                      Icons.school,
                      size: 30.0,
                      color: Colors.white,
                    ),
                  ),
                  const SizedBox(width: 12.0),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Text(
                        "欢迎",
                        style: TextStyle(
                          fontSize: 32.0,
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      Text(
                        "考培系统",
                        style: TextStyle(
                          fontSize: 16.0,
                          color: Colors.white.withOpacity(0.9),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            const SizedBox(height: 16.0),
            // 主内容区
            Expanded(
              child: Container(
                width: double.infinity,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(borderRadius),
                    topRight: Radius.circular(borderRadius),
                  ),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.1),
                      blurRadius: 10,
                      offset: const Offset(0, -4),
                    ),
                  ],
                ),
                child: Padding(
                  padding: EdgeInsets.all(standardSpacing),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      // App logo - 减小尺寸
                      Container(
                        height: 120.0,
                        width: 120.0,
                        decoration: BoxDecoration(
                          color: Colors.blue.shade50,
                          shape: BoxShape.circle,
                          boxShadow: [
                            BoxShadow(
                              color: Colors.blue.withOpacity(0.2),
                              blurRadius: 8,
                              spreadRadius: 2,
                            ),
                          ],
                        ),
                        child: Icon(
                          Icons.school,
                          size: 60.0,
                          color: Colors.blue.shade800,
                        ),
                      ),
                      // App features - 减小间距和边距
                      Container(
                        width: double.infinity,
                        padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 16.0),
                        decoration: BoxDecoration(
                          color: Colors.blue.shade50,
                          borderRadius: BorderRadius.circular(12.0),
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            _buildFeatureRow(Icons.edit, "丰富的题型"),
                            const SizedBox(height: 8.0),
                            _buildFeatureRow(Icons.timer, "定时考试模式"),
                            const SizedBox(height: 8.0),
                            _buildFeatureRow(Icons.assessment, "成绩分析报告"),
                          ],
                        ),
                      ),
                      // 登录按钮
                      SizedBox(
                        width: double.infinity,
                        height: 48.0,
                        child: ElevatedButton.icon(
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.blue.shade900,
                            foregroundColor: Colors.white,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(25.0),
                            ),
                            padding: const EdgeInsets.symmetric(
                              vertical: 10.0,
                              horizontal: 20.0,
                            ),
                            elevation: 5,
                            textStyle: const TextStyle(
                              fontSize: 16.0,
                              fontWeight: FontWeight.bold,
                              color: Colors.white,
                            ),
                          ),
                          icon: const Icon(
                            Icons.login_rounded,
                            size: 22.0,
                          ),
                          onPressed: () {
                            // 跳转到登录页面
                            Navigator.pushNamed(context, '/login');
                          },
                          label: const Text(
                            "登录系统开始考试",
                            textAlign: TextAlign.center,
                            style: TextStyle(
                              fontSize: 16.0,
                              fontWeight: FontWeight.bold,
                              color: Colors.white,
                            ),
                          ),
                        ),
                      ),
                      // 底部填充空间，确保按钮不会太靠底
                      const SizedBox(height: 10.0),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
  
  Widget _buildFeatureRow(IconData icon, String text) {
    return Row(
      children: [
        Container(
          width: 28.0,
          height: 28.0,
          decoration: BoxDecoration(
            color: Colors.blue.shade100,
            shape: BoxShape.circle,
          ),
          child: Icon(icon, color: Colors.blue.shade800, size: 16.0),
        ),
        const SizedBox(width: 10.0),
        Text(
          text,
          style: const TextStyle(
            fontSize: 14.0,
            fontWeight: FontWeight.w500,
          ),
        ),
      ],
    );
  }
} 